package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Message;
import com.kaishengit.util.db.DBHelp;
import com.kaishengit.util.db.Page;
import com.kaishengit.util.db.RowMapper;

public class MessageDao {
	private DBHelp<Message> db = new DBHelp<Message>();
	
	public void save(Message m) {
		String sql = "insert into t_message (id,content,createtime,projectid,userid) values(?,?,?,?,?)";
		db.executeQuery(sql, m.getId(),m.getContent(),m.getCreatetime(),m.getProjectId(),m.getUserId());
	}
	public Page<Message> findByPage(String projectId,int pageNum){
		Page<Message> page = new Page<Message>(count(),pageNum);
		String sql = "select id,content,createtime,projectid,userid from t_message where projectid in(select id from t_project where id = ?) limit ?,?";
		List<Message> list = db.executeQueryToList(sql,new MessageRowMapper(),projectId,page.getStart(),page.getPageSize());
		page.setList(list);
		return page;
		
	}
	private int count() {
		String sql = "select count(*) from t_message";
		return db.executeQuery(sql).intValue();
	}
	public class MessageRowMapper implements RowMapper<Message>{

		public Message mapRow(ResultSet rs) throws SQLException {
			Message m = new Message();
			m.setId(rs.getString("id"));
			m.setContent(rs.getString("content"));
			m.setCreatetime(rs.getString("createtime"));
			m.setProjectId(rs.getString("projectid"));
			m.setUserId(rs.getString("userid"));
			return m;
		}
		
	}
}
